/**
 * 
 */
package info.sswap.ontologies.modularity.owlapi;

import java.util.HashSet;
import java.util.Set;

import org.coode.owlapi.rdf.model.RDFNode;
import org.coode.owlapi.rdf.model.RDFResourceNode;
import org.coode.owlapi.rdf.model.RDFTranslator;
import org.semanticweb.owlapi.model.OWLAxiom;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyManager;

import com.hp.hpl.jena.rdf.model.AnonId;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;


/**
 * Translates an OWL API ontology into a Jena model
 * 
 * @author Pavel Klinov
 *
 */
public class OWLAPIToJenaTranslator extends RDFTranslator/*<RDFNode, Resource, Property, Literal>*/ {

	private Model mModel = null;
	private Set<Resource> mSignature = null;
	private OWLOntology mOntology = null;
	
	public OWLAPIToJenaTranslator(OWLOntologyManager mgr, OWLOntology ontology) {
		super(mgr, ontology, false);
		mOntology = ontology;
	}
	
	private void convertModel() {
		mModel = ModelFactory.createDefaultModel();
		mSignature = new HashSet<Resource>();
		
		for (OWLAxiom axiom : mOntology.getAxioms()) {
			axiom.accept(this);
		}
	}
	
	public Model getModel() {
		
		if (mModel == null) {
			convertModel();
		}
		return mModel;
	}
	
	public Set<Resource> getSignature() {
		
		if (mSignature == null) {
			convertModel();
		}
		return mSignature;
	}

	@Override
	protected void addTriple(RDFResourceNode subj, RDFResourceNode prop, RDFNode obj) {
		
		Resource subject = subj.isAnonymous() ? mModel.createResource(new AnonId(subj.toString())) : mModel.createResource(subj.getIRI().toString());
		Property predicate = mModel.createProperty(prop.getIRI().toString());
		com.hp.hpl.jena.rdf.model.RDFNode object = null;
		
		if (obj.isLiteral()) {
			
			String lexValue = obj.toString();
			
			if (lexValue.startsWith("\"") && lexValue.endsWith("\"") && lexValue.length() > 1) {
				lexValue = lexValue.substring(1, lexValue.length() - 1);
			}
			
			object = mModel.createLiteral(lexValue);
		}
		else {
			if (obj.isAnonymous()) {
				object =  mModel.createResource(new AnonId(obj.toString()));
			}
			else {
				object =  mModel.createResource(obj.getIRI().toString());
				mSignature.add((Resource)object);
			}
		}
		
		mSignature.add(subject);
		mSignature.add(predicate);
		mModel.add(mModel.createStatement(subject, predicate, object));
	}
}
